# -*- coding: utf-8 -*-
from MyApi import *
import time
import configparser

timeavgcalc = [0, 0, 0]

logfh = open('./latency.log', 'w')

logtitle = ["seqnum", "CTPOnRtnGap", "ExchOnRtnGap", "CurrCTPavg", "CurrExchavg", "TimeGapavg", "SendTime", "CTPOnRtnTime", "ExchOnRtnTime"]

logfh.write(','.join(logtitle) + '\n')

def avgcalc(timecalclist):
	timeavgcalc[0] += timecalclist[3]
	timeavgcalc[1] += timecalclist[4]
	timeavgcalc[2] += 1
	ctplatency = timeavgcalc[0] / timeavgcalc[2]
	exlatency = timeavgcalc[1] / timeavgcalc[2]

	print("Number of samples:", timeavgcalc[2])
	print("CTP OnRtn average latency:", round(ctplatency, 3))
	print("Exchange OnRtn average latency:", round(exlatency, 3))
	print("Diff OnRtn average timegap(Exch latency - CTP latency):", round(exlatency - ctplatency, 3))
	sendtime = time.strftime("%Y%m%d-%H:%M:%S.", time.localtime(timecalclist[0])) + str(timecalclist[0]).split('.')[1]
	ctprtntime = time.strftime("%Y%m%d-%H:%M:%S.", time.localtime(timecalclist[1])) + str(timecalclist[1]).split('.')[1]
	exchrtntime = time.strftime("%Y%m%d-%H:%M:%S.", time.localtime(timecalclist[2])) + str(timecalclist[2]).split('.')[1]
	currlogline = [timeavgcalc[2], timecalclist[3], timecalclist[4], round(ctplatency, 3), round(exlatency, 3), round(exlatency - ctplatency, 3), sendtime, ctprtntime, exchrtntime]
	logfh.write(','.join([str(x) for x in currlogline]) + '\n')
	logfh.flush()



def main():
	actionlist = []

	print("create api ins")
	#create trade api
	tradeins = CTradeApi()
	tradeins.start()
	tradeins.ReqAuth()
	tradeins.ReqLogin()
	tradeins.ReqSettleCf()


	while True:
		timecalclist = tradeins.ReqOrIn()
		#print(timecalclist)
		avgcalc(timecalclist)
		time.sleep(INSERTFREQ)




if __name__ == '__main__':
	main()
